package network.io;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import network.NetworkInterface;
import Signals.AbstractMessage;
import Signals.TextMessage;
import Signals.typeContenu;

public class UDPSender implements Runnable {

	private static final String BROADCAST_ADDRESS = "255.255.255.255";
	private static final int BUFFER_LENGTH = 1024;
	private NetworkInterface networkInterface;

	public UDPSender(NetworkInterface networkInterface) throws IOException {
		this.setNetworkInterface(networkInterface);
	}

	public void sendUnicast (AbstractMessage message, InetAddress address) throws IOException {
		byte[] buf = new byte[BUFFER_LENGTH];
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream out = new ObjectOutputStream(bos);

		out.writeObject(message);
		buf = bos.toByteArray();
		DatagramPacket packet = new DatagramPacket(buf, buf.length, address, this.getNetworkInterface().getPort());
		this.getNetworkInterface().getSocket().send(packet);
		if(message.getTypeContenu() == typeContenu.TEXTMESSAGE) {
			TextMessage tm = (TextMessage) message;
			System.out.println("Envoi TEXTMESSAGE vers " + address.getHostAddress() + " ==> " + tm.getMessage());
		} else {
			System.out.println("Envoi " + message.getTypeContenu() + " vers " + address.getHostAddress());
		}
	}
	
	public void sendBroadcast (AbstractMessage message) {
		try {
			this.networkInterface.getSocket().setBroadcast(true);
			this.sendUnicast (message, InetAddress.getByName(BROADCAST_ADDRESS));
			this.networkInterface.getSocket().setBroadcast(false);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void sendConnectedUsers (AbstractMessage message) {
		for(String key : networkInterface.getConnectedUsers())
			try {
				networkInterface.getSendManager().sendUnicast(message, InetAddress.getByName(networkInterface.parseIP(key)));
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}

	public NetworkInterface getNetworkInterface() {
		return networkInterface;
	}


	public void setNetworkInterface(NetworkInterface networkInterface) {
		this.networkInterface = networkInterface;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		
	}
}
